<script setup>
defineOptions({
  name: 'Threejs2'
})
import { onMounted, ref } from 'vue'
import * as Cesium from 'cesium'
import 'cesium/Build/Cesium/Widgets/widgets.css'
import { Dialog } from '@/components/Dialog'

let viewer = null
let boatEntity = null
const boatEntityNum = null
const startPosition = Cesium.Cartesian3.fromDegrees(114.228349639279, 30.66939394252474, 0)
const endPosition = Cesium.Cartesian3.fromDegrees(114.29199265676226, 30.65382824937612, 100)
// const endPosition = Cesium.Cartesian3.fromDegrees(121.800921, 31.30012, 0)
const duration = 1 * 60 * 1000 // 移动持续时间（毫秒）

onMounted(() => {
  // 设置 Cesium Ion 的 Access Token
  // Cesium.Ion.defaultAccessToken =
  //   'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI1YmYwYzdiNy1mOWQ5LTRiY2YtYWI1ZS0yMmMxMzNhYjUxYmQiLCJpZCI6MTkxNTc5LCJpYXQiOjE3MDYwNjY0Nzl9.hb31t0PlQP1ty-DYGNny7H2B8qFpqFprpJ6cRc2z_Hc'
  // const arcGisTerrain = new Cesium.ArcGISTiledElevationTerrainProvider({
  //   url: 'https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer'
  // })
  // 初始化Cesium Viewer
  viewer = new Cesium.Viewer('cesium-container', {
    baseLayerPicker: false, // 禁用底图选择器
    geocoder: false, // 禁用地理编码器（搜索框）
    homeButton: false, // 禁用主页按钮
    sceneModePicker: false, // 禁用场景模式选择器
    timeline: true, // 禁用时间线控件
    animation: true, // 启用动画控件
    shouldAnimate: false, // 自动播放动画
    infoBox: false, // 禁用默认信息框
    selectionIndicator: false // 禁用选择指示器
    // imageryProvider: Cesium.createWorldImagery({
    //   // 影像图层
    //   style: Cesium.IonWorldImageryStyle.AERIAL_WITH_LABELS
    // }),
  })

  // 移除默认的 Cesium 水印（可选）
  viewer.cesiumWidget.creditContainer.style.display = 'none'

  // 移除默认的SkyBox
  viewer.scene.skyBox.show = false
  viewer.scene.backgroundColor = Cesium.Color.TRANSPARENT

  viewer.scene.globe.depthTestAgainstTerrain = true
  viewer.scene.requestRenderMode = true

  Cesium.GeoJsonDataSource.load('models/river84.json').then(function (dataSource) {
    viewer.dataSources.add(dataSource)
    viewer.zoomTo(dataSource)
  })
  Cesium.GeoJsonDataSource.load(
    'http://localhost:8085/geoserver/yh/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=yh%3A%E9%AB%98%E9%80%9F%E8%B7%AF%E9%9D%A21&outputFormat=application%2Fjson&maxFeatures=50'
  ).then(function (dataSource) {
    viewer.dataSources.add(dataSource)
    viewer.zoomTo(dataSource)
  })

  Cesium.Timeline.prototype.makeLabel = CesiumDateTimeFormatter
  viewer.animation.viewModel.dateFormatter = CesiumDateFormatter
  viewer.animation.viewModel.timeFormatter = CesiumTimeFormatter

  // 添加模型
  addBoatModel()

  // 设置相机位置
  viewer.camera.setView({
    destination: Cesium.Cartesian3.fromDegrees(114.228349639279, 30.66939394252474, 2000),
    orientation: {
      heading: Cesium.Math.toRadians(0),
      pitch: Cesium.Math.toRadians(-30),
      roll: 0
    }
  })

  // 添加轨迹线：
  viewer.entities.add({
    polyline: {
      positions: [startPosition, endPosition],
      width: 2,
      material: Cesium.Color.YELLOW
    }
  })

  // 在渲染循环中监听位置变化
  // viewer.scene.postRender.addEventListener(() => {
  //   if (boatEntity) {
  //     const pos = Cesium.Cartographic.fromCartesian(
  //       boatEntity.position.getValue(viewer.clock.currentTime)
  //     )
  //     console.log(
  //       '当前坐标:',
  //       Cesium.Math.toDegrees(pos.longitude).toFixed(6),
  //       Cesium.Math.toDegrees(pos.latitude).toFixed(6)
  //     )
  //   }
  // })

  // 开始移动
  // setTimeout(startSmoothMove, 3000)
  // setTimeout(rotateBoat, 3000)
})

/** 添加模型 */
const addBoatModel = () => {
  let modelEntity = null
  boatEntity = viewer.entities.add({
    position: startPosition,
    model: {
      uri: '/models/boat.glb', // 确保模型文件放在public/models目录
      minimumPixelSize: 0.00001,
      maximumScale: 1,
      runAnimations: false,
      lightColor: Cesium.Color.CRIMSON,

      readyEvent: (e) => console.log('模型已加载', e),
      error: (e) => console.error('模型加载失败', e)
    },
    orientation: Cesium.Transforms.headingPitchRollQuaternion(
      startPosition,
      new Cesium.HeadingPitchRoll(Cesium.Math.toRadians(-40), 0, 0)
    )
    // new Cesium.HeadingPitchRoll(
    //   Cesium.Math.toRadians(90), // 航向 (0=北, 90=东)
    //   0, // 俯仰角（上下点头）
    //   0  // 翻滚角（左右倾斜）
    // )
  })
  customEntities.add(boatEntity.id) // 记录自定义实体ID

  modelEntity = viewer.entities.add({
    position: endPosition,
    model: {
      uri: '/models/boat.glb', // 确保模型文件放在public/models目录
      minimumPixelSize: 1,
      maximumScale: 100,
      runAnimations: false,
      lightColor: Cesium.Color.DARKGREEN,

      readyEvent: (e) => console.log('模型已加载', e),
      error: (e) => console.error('模型加载失败', e)
    },
    orientation: Cesium.Transforms.headingPitchRollQuaternion(
      startPosition,
      new Cesium.HeadingPitchRoll(Cesium.Math.toRadians(-40), 0, 0)
    )
    // new Cesium.HeadingPitchRoll(
    //   Cesium.Math.toRadians(90), // 航向 (0=北, 90=东)
    //   0, // 俯仰角（上下点头）
    //   0  // 翻滚角（左右倾斜）
    // )
  })
  customEntities.add(modelEntity.id) // 记录自定义实体ID

  modelEntity = viewer.entities.add({
    name: '标注1',
    position: Cesium.Cartesian3.fromDegrees(114.2599265676226, 30.65382824937612, 2),
    point: {
      pixelSize: 15,
      color: Cesium.Color.RED
    },
    label: {
      text: '标注1',
      font: '14pt sans-serif',
      style: Cesium.LabelStyle.FILL_AND_OUTLINE,
      outlineWidth: 2,
      verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
      pixelOffset: new Cesium.Cartesian2(0, -15)
    },
    customData: {
      title: '标注1',
      content: '高度：468米<br>建成时间：1994年'
    }
  })
  customEntities.add(modelEntity.id) // 记录自定义实体ID

  addSampleEntities()
  setupClickHandler()
}

const setupClickHandler = () => {
  const handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas)

  handler.setInputAction((click) => {
    const pickedObject = viewer.scene.pick(click.position)
    console.log('pickedObject', pickedObject)

    if (pickedObject && pickedObject.id && customEntities.has(pickedObject.id.id)) {
      // 点击自定义实体
      showEntityPopup(pickedObject.id)
    } else {
      // 点击其他位置
      showCoordinatePopup(click.position)
    }
  }, Cesium.ScreenSpaceEventType.LEFT_CLICK)
}

const showEntityPopup = (entity) => {
  popupTitle.value = (entity.customData && entity.customData.title) || entity.name || '未知'
  popupText.value = (entity.customData && entity.customData.content) || '没有更多信息'
  popupVisible.value = true

  // 添加闪烁效果
  const originalColor = entity.point.color.getValue()
  let flashState = true
  const interval = setInterval(() => {
    entity.point.color = flashState ? Cesium.Color.YELLOW : originalColor
    flashState = !flashState
  }, 500)

  // 清除闪烁
  setTimeout(() => {
    clearInterval(interval)
    entity.point.color = originalColor
  }, 2500)
}

const showCoordinatePopup = (clickPosition) => {
  const cartesian = viewer.scene.camera.pickEllipsoid(clickPosition, viewer.scene.globe.ellipsoid)

  if (cartesian) {
    const cartographic = Cesium.Cartographic.fromCartesian(cartesian)
    const longitude = Cesium.Math.toDegrees(cartographic.longitude).toFixed(6)
    const latitude = Cesium.Math.toDegrees(cartographic.latitude).toFixed(6)
    const height = viewer.scene.globe.getHeight(cartographic) || 0

    popupTitle.value = '坐标信息'
    popupText.value = `
          经度: ${longitude}<br>
          纬度: ${latitude}<br>
          海拔: ${height.toFixed(2)}米
        `
    popupVisible.value = true
  }
}

const closePopup = () => {
  popupVisible.value = false
}

/** 开始移动 */
const startSmoothMove = () => {
  const startTime = Cesium.JulianDate.fromDate(new Date())
  const stopTime = Cesium.JulianDate.addSeconds(startTime, duration / 1000, new Cesium.JulianDate())
  // 重置位置属性
  boatEntity.position = new Cesium.SampledPositionProperty()

  // 添加关键帧
  boatEntity.position.addSample(startTime, startPosition)
  boatEntity.position.addSample(stopTime, endPosition)

  // 设置方向插值（保持航向）
  // boatEntity.orientation = new Cesium.VelocityOrientationProperty(boatEntity.position)

  // 配置时钟
  viewer.clock.startTime = startTime.clone()
  viewer.clock.stopTime = stopTime.clone()
  viewer.clock.currentTime = startTime.clone()
  viewer.clock.clockRange = Cesium.ClockRange.LOOP_STOP
  viewer.clock.multiplier = 1
  viewer.clock.shouldAnimate = true

  // 启用速度方向跟踪
  // boatEntity.orientation = new Cesium.VelocityOrientationProperty(boatEntity.position)
  boatEntity.orientation = undefined

  // 定位跟踪
  // viewer.trackedEntity = boatEntity
}

// 平滑旋转动画
const rotateBoat = () => {
  // 旋转动画逻辑
  // 创建航向插值动画（90度到180度，持续3秒）
  const startTime = Cesium.JulianDate.fromDate(new Date())
  const duration = 3
  const endTime = Cesium.JulianDate.addSeconds(startTime, duration, new Cesium.JulianDate())

  const headingProperty = new Cesium.SampledProperty(Number)
  headingProperty.addSample(startTime, Cesium.Math.toRadians(0)) // 初始角度
  headingProperty.addSample(endTime, Cesium.Math.toRadians(180)) // 目标角度
  console.log(
    '11111',
    boatEntity.position.getValue(Cesium.JulianDate.now()),

    new Cesium.HeadingPitchRoll(headingProperty.getValue(Cesium.JulianDate.now()), 0, 0)
  )
  console.log('2222', Cesium.HeightReference.RELATIVE_TO_GROUND)

  boatEntity.orientation = new Cesium.CallbackProperty(() => {
    return Cesium.Transforms.headingPitchRollQuaternion(
      boatEntity.position.getValue(Cesium.JulianDate.now()),
      new Cesium.HeadingPitchRoll(headingProperty.getValue(Cesium.JulianDate.now()), 0, 0)
    )
  }, false)
}

//cesium时钟时间格式化
const CesiumTimeFormatter = (datetime, viewModel) => {
  const julianDT = new Cesium.JulianDate()
  Cesium.JulianDate.addHours(datetime, 8, julianDT)
  const gregorianDT = Cesium.JulianDate.toGregorianDate(julianDT)

  const hour = gregorianDT.hour + ''
  const minute = gregorianDT.minute + ''
  const second = gregorianDT.second + ''
  return `${hour.padStart(2, '0')}:${minute.padStart(2, '0')}:${second.padStart(2, '0')}`
}
//cesium时钟日期格式化
const CesiumDateFormatter = (datetime, viewModel, ignoredate) => {
  const julianDT = new Cesium.JulianDate()
  Cesium.JulianDate.addHours(datetime, 8, julianDT)
  const gregorianDT = Cesium.JulianDate.toGregorianDate(julianDT)

  return `${gregorianDT.year}年${gregorianDT.month}月${gregorianDT.day}日`
}
//cesium时间轴格式化
const CesiumDateTimeFormatter = (datetime, viewModel, ignoredate) => {
  const julianDT = new Cesium.JulianDate()
  Cesium.JulianDate.addHours(datetime, 8, julianDT)
  const gregorianDT = Cesium.JulianDate.toGregorianDate(julianDT)

  const hour = gregorianDT.hour + ''
  const minute = gregorianDT.minute + ''
  return `${gregorianDT.day}日${hour.padStart(2, '0')}:${minute.padStart(2, '0')}`
}

//使用键盘控制方向
// 在Vue组件中添加事件监听
// let heading = Cesium.Math.toRadians(90)
// const ROTATION_SPEED = 0.15 // 弧度/次

// document.addEventListener('keydown', (e) => {
//   if (!boatEntity) return

//   switch (e.key) {
//     case 'ArrowLeft':
//       heading -= ROTATION_SPEED
//       break
//     case 'ArrowRight':
//       heading += ROTATION_SPEED
//       break
//   }

//   boatEntity.orientation = Cesium.Transforms.headingPitchRollQuaternion(
//     boatEntity.position.getValue(Cesium.JulianDate.now()),
//     new Cesium.HeadingPitchRoll(heading, 0, 0)
//   )
// })

// 弹窗
const popupVisible = ref(false)
const popupTitle = ref('')
const popupText = ref('')
const customEntities = new Set() // 存储自定义实体
/** 添加点 */
const addSampleEntities = () => {
  samplePositions.forEach((pos, index) => {
    const entity = viewer.entities.add({
      ...pos,
      position: pos.position,
      point: {
        pixelSize: 15,
        color: Cesium.Color.RED,
        outlineColor: Cesium.Color.WHITE,
        outlineWidth: 2
      },
      customData: pos.info && pos.info // 存储自定义信息
    })
    customEntities.add(entity.id) // 记录自定义实体ID
  })
}
const samplePositions = [
  {
    position: Cesium.Cartesian3.fromDegrees(114.249767, 30.654189, 50),
    info: {
      title: '上海中心大厦',
      content: '高度：632米<br>建成时间：2015年'
    }
  },
  {
    position: Cesium.Cartesian3.fromDegrees(114.25839, 30.672181, 30),
    info: {
      title: '东方明珠',
      content: '高度：468米<br>建成时间：1994年'
    }
  },
  {
    name: '标注12',
    position: Cesium.Cartesian3.fromDegrees(114.247386, 30.672847, 2),
    label: {
      text: '标注12',
      font: '14pt sans-serif',
      style: Cesium.LabelStyle.FILL_AND_OUTLINE,
      outlineWidth: 2,
      verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
      pixelOffset: new Cesium.Cartesian2(0, -15)
    },
    customData: {
      title: '标注12',
      content: '高度：468米<br>建成时间：1994年'
    }
  },
  {
    position: Cesium.Cartesian3.fromDegrees(114.26234, 30.66146, 2),
    name: '船只目的地',

    point: {
      pixelSize: 10,
      color: Cesium.Color.RED
    },
    label: {
      text: '船只目的地',
      // font: '14px sans-serif',
      // style: Cesium.LabelStyle.FILL_AND_OUTLINE,
      verticalOrigin: Cesium.VerticalOrigin.BOTTOM, // 确保标签相对于点的位置设置正确
      heightReference: Cesium.HeightReference.RELATIVE_TO_GROUND,

      showBackground: false,
      backgroundColor: Cesium.Color.BLACK
      // backgroundPadding: new Cesium.Cartesian2(15, 15)
    },
    customData: {
      title: '船只目的地',
      content: '长度：618米<br>建成时间：1894年'
    }
  },
  {
    name: '武汉',
    position: Cesium.Cartesian3.fromDegrees(114.262324, 30.626366, 2),
    point: {
      pixelSize: 15,
      color: Cesium.Color.BLUE
    },
    label: {
      text: '武汉',
      font: '14pt sans-serif',
      style: Cesium.LabelStyle.FILL_AND_OUTLINE,
      outlineWidth: 2,
      verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
      pixelOffset: new Cesium.Cartesian2(0, -15)
    },
    customData: {
      title: '武汉',
      content: '高度：618米<br>建成时间：1894年'
    }
  }
]
</script>

<template>
  <div id="cesium-container" style="width: 100%; height: 800px"></div>
  <!-- 信息弹窗 -->
  <Dialog
    class="cesium-popup"
    v-model="popupVisible"
    :title="popupTitle"
    width="500"
    style="transform: translateX(100%)"
  >
    <div class="popup-content">
      <h3>{{ popupTitle }}</h3>
      <p v-html="popupText"></p>
      <BaseButton @click="closePopup">关闭</BaseButton>
    </div>
  </Dialog>
</template>

<style lang="less" scoped></style>
